package es.udc.pfc.davidparedes.web.pages.user;

import java.util.Calendar;
import java.util.Date;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import es.udc.pfc.davidparedes.model.receptionist.Receptionist;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;

import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.DIRECTOR)
public class UpdateReceptionist {
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Property
    private Receptionist receptionist;
    
    @Property
    private Long updateReceptionistId;
    
    @Property
    private Long removeReceptionistId;

    @Property
    private String firstName;

    @Property
    private String lastName;

    @Property
    private String email;
    
    @Property
    private String nif;
    
    @Property
    private Date contractTerminationDate;
    
    @Component
    private Form updateReceptionistForm;
    
    @Component
    private Form removeReceptionistForm;
    
    
    void onActivate(Long id) {
    	try {
       		
    		receptionist = userService.findReceptionist(id);
    		updateReceptionistId = removeReceptionistId = id;
    		
    		firstName = receptionist.getFirstName();
    		lastName = receptionist.getLastName();
    		email = receptionist.getEmail();
    		nif = receptionist.getNif();
    		contractTerminationDate = receptionist.getContractTermination().getTime();
    		
			} catch (InstanceNotFoundException e) {
		}
    }

    Object onValidateFromUpdateReceptionistForm() throws InstanceNotFoundException {
    	
        if (!updateReceptionistForm.isValid()) {
            return this;
        }
        
    	Calendar contractTermination = Calendar.getInstance();
    	contractTermination.setTime(contractTerminationDate);
    
		userService.findReceptionist(updateReceptionistId);
        userService.updateReceptionist(updateReceptionistId, firstName, lastName, email, nif, contractTermination);
        
        return ManageUM.class;
    }
    
    Object onValidateFromRemoveReceptionistForm() throws InstanceNotFoundException {
    	userService.deactivateReceptionist(removeReceptionistId);
    	return ManageUM.class;
    }

}
